package com.otod.pm.prj.web;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.otod.base.exception.AppException;
import com.otod.base.json.JsonFailure;
import com.otod.base.json.JsonSuccess;
import com.otod.commons.auth.SessionUserHolder;
import com.otod.commons.auth.SessionUserUtil;
import com.otod.commons.constants.CommonConstant;
import com.otod.commons.entity.Page;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.StringUtils;
import com.otod.commons.web.BaseController;
import com.otod.pm.comment.service.SubmitInfoService;
import com.otod.pm.comment.vo.AsmgSubmitInfoVo;
import com.otod.pm.constants.PmConstant;
import com.otod.pm.prj.bo.DetailCfgFiledBo;
import com.otod.pm.prj.bo.PrjFruitFileBo;
import com.otod.pm.prj.bo.PrjViewBo;
import com.otod.pm.prj.bo.StepBo;
import com.otod.pm.prj.service.DetailService;
import com.otod.pm.prj.service.ProjectService;
import com.otod.pm.prj.service.StepService;
import com.otod.pm.prj.service.TaskService;
import com.otod.pm.prj.service.TeamService;
import com.otod.pm.prj.vo.DetailVo;
import com.otod.pm.prj.vo.ProjectVo;
import com.otod.pm.prj.vo.StepVo;
import com.otod.pm.prj.vo.TaskVo;
import com.otod.pm.prj.vo.TeamVo;
import com.otod.sys.amcm.service.AmcmMsgAppService;
import com.otod.sys.file.service.impl.FileServiceImpl;
import com.otod.sys.vo.FileVo;

/**
 * 项目管理
 * @author yiChen
 * 2014-4-29 添加了一个通过项目名称查询id的方法 方法名字是selectProjectUuid     添加人longjinwei
 * 2014-4-29 修改过savePrj()方法
 *
 */

@Controller
@RequestMapping("pm/project")
public class ProjectController extends BaseController {

	@Autowired
	private ProjectService projectService;
	@Autowired
	private DetailService detailService;
	@Autowired
	private TeamService teamService;
	@Autowired
	private StepService stepService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private SubmitInfoService submitInfoService;
	
	@Autowired
	private FileServiceImpl fileService;
	
	
	

	/**
	 * 查询所有项目
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "findAll", method = RequestMethod.POST)
	@ResponseBody
	public List<ProjectVo> findAll() {
		List<ProjectVo> projectList = projectService.findAll();
		return projectList;
	}
	
	/**
	 * 查询所有可选择的项目
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "selectAll", method = RequestMethod.POST)
	@ResponseBody
	public List<ProjectVo> selectAll(HttpServletRequest request)  {
		List<ProjectVo> projectList = projectService.findAll();
		return projectList;
	}
	
	
	
	/**
	 * 项目查询方法
	 * @param request
	 * @return
	 */
	@RequestMapping(value="query",method=RequestMethod.GET)
	@ResponseBody
	public List<ProjectVo> query(HttpServletRequest request){
		Map params = super.getParamMapFromRequest(request);
		return projectService.queryForList(params);
	}
	
	
	
	/**
	 * 项目展示
	 * @param prjId	项目ID 
	 * @return	PrjViewBo
	 * @author jqiu
	 * @throws AppException 
	 */
	@RequestMapping(value="viewPrjInfo",method=RequestMethod.POST)
	@ResponseBody
	public PrjViewBo viewPrjInfo(@RequestBody String prjId) throws AppException {
		if(StringUtils.isEmpty(prjId)){
			throw new AppException("项目编号不能为空！");
		}
		
		PrjViewBo vo = new PrjViewBo();
		
		ProjectVo prjVo = projectService.getById(prjId);
		
		
		vo.setPrjVo(prjVo);
		
		List<DetailCfgFiledBo> detailCfgList = detailService.detailCfgListVo2Bo(detailService.selectDetailPrjType(prjVo.getPrjType()));
		vo.setDetailCfgList(detailCfgList);
		
		DetailVo detailVo = null;
		if(Collections3.isNotEmpty(detailCfgList)){
			detailVo = detailService.selectDetail(prjId,detailCfgList.get(0).getVersion());
		}
		vo.setDetailVo(detailVo);
		
		SessionUserHolder sessionUser = SessionUserUtil.getCurrentUser();
		String userNo = sessionUser.getUserNo();
		
		List<StepBo> stepList = stepService.queryStepList(prjId,userNo);
		vo.setStepList(stepList);
		
		vo.setPrjRole(teamService.getRoleInTeam(prjId, userNo));
		
		List<TeamVo> teamList = teamService.findByPrjId(prjId);
		vo.setTeamList(teamList);
		
		vo.setUserNo(userNo);
		return vo;
   }
	
	
	
	/**
	 * 根据项目ID获取角色信息
	 * @param id
	 * @author jqiu
	 * @return
	 */
	@RequestMapping(value="getprojectById",method=RequestMethod.POST)
	@ResponseBody
	public ProjectVo getProjectById(String id) {	
		ProjectVo vo = projectService.getById(id);
		return vo;
	}
	/**
	 * 开始项目
	 * @param prjId
	 * @author yiChen
	 * @return
	 * @throws AppException 
	 */
	@RequestMapping(value="beginProject",method=RequestMethod.POST)
	@ResponseBody
	public String beginProject(@RequestBody String prjId) throws AppException {	
		SessionUserHolder sessionUser = SessionUserUtil.getCurrentUser();
		String userNo = sessionUser.getUserNo();
		boolean flag = submitInfoService.beginProject(prjId,userNo);
		if(flag){
			//通过
			ProjectVo vo = projectService.getById(prjId);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("uuid", vo.getUuid());
			map.put("startDate", DateUtils.getCurrentDate());
			map.put("status", PmConstant.PRJ_STATUS_STARTING);
			super.setUpdateOperInfo(map);
			projectService.beginProject(map);//TODO 项目开始任务提醒
			
			
			
			
		}else{
			return JsonFailure.factory("项目未审核完成或审核失败，不能开始项目");
		}
		return JsonSuccess.factory("开始项目成功！");
	}

	
	/**
	 * 保存项目信息 修改项目信息
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="savePrj",method=RequestMethod.POST)
	@ResponseBody
	public ProjectVo savePrj(ProjectVo vo,DetailVo detailVo, String radio, HttpServletRequest request) throws Exception {

		//得到最大版本号码
		//String cfgVersion=request.getParameter("cfgVersion");
		//如果前台输入数据有误 就会有异常
		if(null == vo){
			throw new AppException("项目信息不能为空！");
		}
		if(null != vo.getUuid() && !"".equals(vo.getUuid())){
			//更新
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("uuid", vo.getUuid());
			map.put("prjLvl", vo.getPrjLvl());
			map.put("custNo", vo.getCustNo());
			map.put("prjNo", vo.getPrjNo());
			map.put("depict", vo.getDepict());
			// map.put("startDate", vo.getStartDate());
			map.put("endDate", vo.getEndDate());
			map.put("prjName", vo.getPrjName());
			map.put("invest", vo.getInvest());
			map.put("investment", vo.getInvestment());
			map.put("contracts", vo.getContracts());
			map.put("contractno", vo.getContractno());
			map.put("projectSize", vo.getProjectSize());
			map.put("takeUnit", vo.getTakeUnit());
			super.setUpdateOperInfo(map);
			projectService.updatePrj(map);
			
			//得到项目表的uuid 由于 DetailVo ProjectVo有相同的uuid 需重新得到
			detailVo.setUuid(request.getParameter("detailUuid"));
			detailVo.setPrjId(vo.getUuid());
			detailService.updateDetail(baseDetaIlVoUpdate(baseDetaIlVoAdd(detailVo, radio)));
			
			return vo;
		}else{
			//新增
			
			vo.setPrjType(vo.getPrjType()); 
			//查询是否有在同种类型下同名的项目
			super.setInsertOperInfo(vo);
			projectService.addPrj(vo);
			//得到project表中的uuid 通过类型 和名字查询
			ProjectVo projectVo = projectService.selectProject(vo.getPrjType(),vo.getPrjName());
			//设置项目的id
			detailVo.setPrjId(projectVo.getUuid());
			//设置最大版本号 
			detailVo.setCfgVersion(detailVo.getCfgVersion());
			//保存  产品基本信息
			detailService.saveDetail(baseDetaIlVoAdd(detailVo, radio));
			return projectVo;
		}
	}
	
	/**
	 * 项目查询方法
	 * @param request
	 * @return
	 */
	
	@RequestMapping(value="queryPrj",method=RequestMethod.GET)
	@ResponseBody
	public Page queryPage(HttpServletRequest request,String prj_name){
		Map params = super.getParamMapFromRequest(request);
		if(StringUtils.isNotEmpty(prj_name)){
			params.put("prjName", prj_name);
		}
		SessionUserHolder user = SessionUserUtil.getCurrentUser();
		String empNo = user.getUserNo();
		String roleNo = user.getRoleNo();
		params.put("empNo", empNo);
		Page page = new Page(request);
		return projectService.queryForList(page,params);
	}
	
	/**
	 * 删除项目
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="delPrjs",method=RequestMethod.GET)
	@ResponseBody
	public String delPrjs(String projectId){
		if(StringUtils.isEmpty(projectId)){
			return JsonFailure.factory("请选择要删除的项目");
		}
		projectService.delPrj(projectId);
		return JsonSuccess.factory("删除项目成功");
	}
	
	/**
	 * 保存项目人员信息
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="saveTeam",method=RequestMethod.POST)
	@ResponseBody
	public String saveTeam(TeamVo vo) {
		if(null != vo){
			if(null != vo.getUuid() && !"".equals(vo.getUuid())){
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("uuid", vo.getUuid());
				map.put("prjId", vo.getPrjId());
				map.put("empNo", vo.getEmpNo());
				map.put("roleNo", vo.getRoleNo());
				map.put("startDate", vo.getStartDate());
				map.put("endDate", vo.getEndDate());
				map.put("status", vo.getStatus());
				map.put("remark", vo.getRemark());
				//修改过可能有问题
				teamService.updateTeam(map);
				//projectService.updateTeam(map);
			}else{
				//新增
				//修改过可能有问题
				teamService.addTeam(vo);
				//projectService.addTeam(vo);
			}
		}
		return JsonSuccess.factory("保存人员成功");
	}
	
	/**
	 * 保存项目阶段信息
	 * @param vo
	 * @return
	 * @throws AppException 
	 */
	@RequestMapping(value="saveStep",method=RequestMethod.POST)
	@ResponseBody
	public String saveStep(StepVo vo) throws AppException {
		
		if(null != vo){
			if(null != vo.getUuid() && !"".equals(vo.getUuid())){
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("uuid", vo.getUuid());
				map.put("stepName", vo.getStepName());
				map.put("prjId", vo.getPrjId());
				map.put("startDate", vo.getStartDate());
				map.put("endDate", vo.getEndDate());
				map.put("status", vo.getStatus());
				map.put("depict", vo.getDepict());
				map.put("sort", vo.getSort());
				map.put("ratio", vo.getRatio());
				
				stepService.update(map);
				//projectService.updateStep(map);
			}else{
				//新增
				stepService.insert(vo);
				//projectService.addPrjStep(vo);
			}
		}
		return JsonSuccess.factory("保存阶段成功");
	}
	
	
	/**
	 * 保存项目阶段信息
	 * @param vo
	 * @return
	 * @throws AppException 
	 */
	@RequestMapping(value="remove",method=RequestMethod.GET)
	@ResponseBody
	public String remove(String projectId) throws AppException {
		Map<String, Object> map = new HashMap<String, Object>();
		super.setUpdateOperInfo(map);
		projectService.removePrj(map, projectId);
		return JsonSuccess.factory("删除成功");
	}
	
	
	
	
	/**
	 * 通过项目类型查询项目名字
	 * @return
	 */
	@RequestMapping(value="selectProjectUuid",method = RequestMethod.GET)
	@ResponseBody
	public ProjectVo selectProjectUuid(String prjType){
		ProjectVo projectVo = projectService.selectProjectUuid(prjType);
		return projectVo;
	}
	
	
	/**
	 * 通过登录人员的EmpNo查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryPrjUuidEmp",method = RequestMethod.POST)
	@ResponseBody
	public List<ProjectVo> queryPrjUuidEmp(HttpServletRequest request){
		String empNo =  SessionUserUtil.getCurrentUser().getUserNo();
		String roleNo =  SessionUserUtil.getCurrentUser().getRoleNo();
		
/*		if("mister".equals(roleNo)||"manager".equals(roleNo)){
			return projectService.queryPrjUuidEmp(empNo, "");
		}*/
		return projectService.queryPrjUuidEmp(empNo, PmConstant.PRJ_STATUS_STARTING);
	}
	
	/**
	 * 通过前台传回empNo查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryPrjEmp",method = RequestMethod.GET)
	@ResponseBody
	public List<ProjectVo> queryPrjEmp(String empNo){
//	String empNo =  SessionUserUtil.getCurrentUser().getUserNo();
//		String roleNo =  SessionUserUtil.getCurrentUser().getRoleNo();
//		if("mister".equals(roleNo)||"manager".equals(roleNo)){
//			return projectService.queryPrjUuidEmp("", "");
//		}
		return projectService.queryPrjUuidEmp(empNo, PmConstant.PRJ_STATUS_STARTING);
	}
	
	/**
	 * 终止项目
	 * @param id 项目id
	 * @return
	 */
	@RequestMapping(value="stopPrj",method = RequestMethod.GET)
	@ResponseBody
	public String stopPrj(String id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uuid", id);
		params.put("status", PmConstant.PRJ_STATUS_STOP);
		projectService.update(params);
		return JsonSuccess.factory("终止项目成功");	
	}
	
	/**
	 * 通过项目Id查询项目成果信息
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value="queryFruitByPrjId",method = RequestMethod.POST)
	@ResponseBody
	public List<PrjFruitFileBo> queryFruitByPrjId(HttpServletRequest request){
		
		String prjId = request.getParameter("prjId");
		List<PrjFruitFileBo> list =  new ArrayList<PrjFruitFileBo>();
		PrjFruitFileBo  bo =  new PrjFruitFileBo();
		ProjectVo vo = projectService.getById(prjId);
		bo.setUuid(vo.getUuid());
		bo.setShowName(vo.getPrjName());
		bo.setFolderType("40010001");
		list.add(bo);
		
		String stepId = request.getParameter("stepId");
		if(StringUtils.isEmpty(stepId)){
			
			//查询出该项目的所有阶段
			List<StepVo> stepList = stepService.queryStepVoList(prjId);
			for (StepVo stepVo : stepList) {
				bo = new PrjFruitFileBo();
				bo.setUuid(stepVo.getUuid());
				bo.setShowName(stepVo.getStepName());
				bo.setParentId(stepVo.getPrjId());
				bo.setFolderType("40010001");
				list.add(bo);
				List<FileVo> fileList = fileService.queryFileByBusiId(stepVo.getUuid());
				for (FileVo fileVo : fileList) {
					bo = new PrjFruitFileBo();
					bo.setUuid(fileVo.getUuid());
					bo.setShowName(fileVo.getFileName());
					bo.setParentId(stepVo.getUuid());
					bo.setFolderType("40010002");
					bo.setStatus(queryStatusByKey(fileVo.getUuid()));
					list.add(bo);
				}
				
			}
		}else{
			StepVo stepVo = stepService.getById(stepId);
			bo = new PrjFruitFileBo();
			bo.setUuid(stepVo.getUuid());
			bo.setShowName(stepVo.getStepName());
			bo.setParentId(stepVo.getPrjId());
			bo.setFolderType("40010001");
			list.add(bo);
			List<FileVo> fileList = fileService.queryFileByBusiId(stepVo.getUuid());
			for (FileVo fileVo : fileList) {
				bo = new PrjFruitFileBo();
				bo.setUuid(fileVo.getUuid());
				bo.setShowName(fileVo.getFileName());
				bo.setParentId(stepVo.getUuid());
				bo.setStatus(queryStatusByKey(fileVo.getUuid()));
				bo.setFolderType("40010002");
				list.add(bo);
			}
		}
		
		return list;
	}
	
	public String queryStatusByKey(String busitableKey){
		String empNo =  SessionUserUtil.getCurrentUser().getUserNo();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("busitableKey", busitableKey);
		map.put("targetEmpNo", empNo);
		List<AsmgSubmitInfoVo> list = submitInfoService.queryForList(map);
		if(Collections3.isEmpty(list)){
			return "";
		}else{
			return list.get(0).getStatus();
		}
	}
	
	
	/**
	 * 通过项目名称 ，类型， 状态 查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="mainPersonQueryForPrj",method = RequestMethod.GET)
	@ResponseBody
	public Page mainPersonQueryForPrj(HttpServletRequest request){
		//项目名称
		String prjName = request.getParameter("prjName");
		String pmProjectStatus = request.getParameter("pmProjectStatus");
		String prjType = request.getParameter("prjType");
		
		List<ProjectVo> projectList = new ArrayList<ProjectVo>();
		Map<String, Object> params = new HashMap<String, Object>();
		//项目名称模糊查询
		params.put("prjName", prjName);
		params.put("prjType", prjType);
		params.put("status", pmProjectStatus);
		params.put("isDel", CommonConstant.COMMON_NO);
		params.put("prjEmpNo", "prjEmpNo");
		Page page = new Page(request);
		page = projectService.queryForList(page,params);
		projectList = page.getAaData();
		for (ProjectVo projectVo : projectList) {
			//通过uuid查询
			params.clear();		
			params.put("prjId", projectVo.getUuid());
			params.put("roleNo", PmConstant.PRJ_ROLE_PRINCIPAL);
			List<TeamVo> teamList = new ArrayList<TeamVo>();
			teamList = teamService.queryForList(params);
			if (Collections3.isEmpty(teamList)) {
				projectVo.setTrainsRoleNo("无");
			} else {
				projectVo.setTrainsRoleNo(teamList.get(0).getEmpName());
			}
		}
		return  page;
		
	}

	
	
	
	
	/************************************处理修改pm_t_detail的基础方法**********************************************/
	
	
	public Map<String, Object> baseDetaIlVoUpdate(DetailVo vo){
		
		Map<String, Object> map = new HashMap<String,Object>();
		
		
		map.put("uuid", vo.getUuid());
		map.put("prjId", vo.getPrjId());
		map.put("cfgVersion", vo.getCfgVersion());
		map.put("prjPlace", vo.getPrjPlace());
		map.put("contacts", vo.getContacts());
		map.put("addr", vo.getAddr());
		map.put("postcode", vo.getPostcode());
		map.put("telephone", vo.getTelephone());
		map.put("undertakeType", vo.getUndertakeType());
		map.put("undertakeUnit", vo.getUndertakeUnit());
		map.put("fax", vo.getFax());
		map.put("dateClmn1", vo.getDateClmn1());
		map.put("dateClmn2", vo.getDateClmn2());
		map.put("dateClmn3", vo.getDateClmn3());
		map.put("dateClmn4", vo.getDateClmn4());
		map.put("decClmn1", vo.getDateClmn1());
		map.put("decClmn2", vo.getDateClmn2());
		map.put("decClmn3", vo.getDateClmn3());
		map.put("decClmn4", vo.getDateClmn4());
		map.put("longClmn1", vo.getLongClmn1());
		map.put("longClmn2", vo.getLongClmn2());
		map.put("longClmn3", vo.getLongClmn3());
		map.put("longClmn4", vo.getLongClmn4());
		
		//varClmn1~varClmn7其中有下拉框 
		
		map.put("varClmn1", vo.getVarClmn1());
		map.put("varClmn2", vo.getVarClmn2());
		map.put("varClmn3", vo.getVarClmn3());
		map.put("varClmn4", vo.getVarClmn4());
		map.put("varClmn5", vo.getVarClmn5());
		map.put("varClmn6", vo.getVarClmn6());
		map.put("varClmn7", vo.getVarClmn7());
		map.put("varClmn8", vo.getVarClmn8());
		return  map;
	}
	
	public DetailVo baseDetaIlVoAdd(DetailVo vo,String radio){
		if(StringUtils.isEmpty(radio)){
			return vo;
		}
		//varClmn1~varClmn7其中有下拉框 
		String[] radioSplit = radio.split(",");
		for (int i = 0; i < radioSplit.length; i++) {
			String[] varClmn = radioSplit[i].split(";");
			if(varClmn[1]=="varClmn1"||"varClmn1".equals(varClmn[1])){
				vo.setVarClmn1(varClmn[0]);
			}else if(varClmn[1]=="varClmn2"||"varClmn2".equals(varClmn[1])){
				vo.setVarClmn2(varClmn[0]);
			}else if(varClmn[1]=="varClmn3"||"varClmn3".equals(varClmn[1])){
				vo.setVarClmn3(varClmn[0]);
			}else if(varClmn[1]=="varClmn4"||"varClmn4".equals(varClmn[1])){
				vo.setVarClmn4(varClmn[0]);
			}else if(varClmn[1]=="varClmn5"||"varClmn5".equals(varClmn[1])){
				vo.setVarClmn5(varClmn[0]);
			}else if(varClmn[1]=="varClmn6"||"varClmn6".equals(varClmn[1])){
				vo.setVarClmn6(varClmn[0]);
			}else if(varClmn[1]=="varClmn7"||"varClmn7".equals(varClmn[1])){
				vo.setVarClmn7(varClmn[0]);
			}else if(varClmn[1]=="varClmn8"||"varClmn8".equals(varClmn[1])){
				vo.setVarClmn8(varClmn[0]);
			}
		}
		return  vo;
	}
}
